package file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadLogic {
	
	public static void download(String filename,
								HttpServletRequest request,
								HttpServletResponse response){
		
		String path = "C:/Upload";
		File f = new File(path+File.separator+filename);
		
		long fileSize = f.length();
	 	response.setContentType("application/download");
	 	response.setContentLength((int)fileSize);
	 	
	 	boolean flag = request.getHeader("user-agent").toUpperCase().indexOf("MSIE")!=-1;
	 	
	 	try{
		 	if(!flag){
		 		
		 		response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "utf-8")); 		
		 	}
		 	else{
		 		response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("utf-8"),"8859_1"));
		 	}
		 	
		 	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
		 	BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
		 	
		 	int data=0;
		 	while((data=bis.read())!=-1){
		 		
		 		bos.write(data);
		 		bos.flush();
		 	}
			bis.close();
			bos.close();
	 	}
	 	catch(Exception e){}
			
	}
	
}
